﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using QntPlatform.BinanceApi;
using QntPlatform.Model;
using QntPlatform.Db;
using QntPlatform.Platform;

namespace QntPlatform
{
    public  interface ISysApi
    {
        int CommandRobotList(string pair, string strategyId, string cmd);
        bool CommandRobot(string robotName, int? robotId, string cmd);
        RobotInfo[] GetRobotList(int offset, int length, int robotStatus, string label);
        bool RestartRobot(long RobotId, Dictionary<string, string> Settings = null);
        bool StopRobot(long RobotId);
        long NewRobot(string robotName, string exchangeId, string pair, string strategyId, Dictionary<string, string> strategyArgs);
        StrategyInfo[] GetStrategyList();
        ExchangeInfo[] GetExchangeList();


        }
    public class SysApi : ISysApi
    {
        public static SysApi Api = new SysApi();
        //public int AccountId { get; set; }
        ILog log = LogManager.GetLogger(typeof(SysApi));

        /// <summary>
        /// 
        /// </summary>
        /// <param name="pair"></param>
        /// <param name="strategyId"></param>
        /// <param name="cmd"></param>
        /// <returns>错误数量</returns>
        public int CommandRobotList(string pair, string strategyId,string cmd)
        {
            if (string.IsNullOrWhiteSpace(cmd))
            {
                throw new ArgumentException("cmd不能为空");
            }
            var rList=  Robot.GetRobots().Where(p => p.RobotInfo.Pair == pair && p.RobotInfo.strategyId == strategyId).ToArray();
            int re = 0;
            if(rList==null||rList.Length==0)
                log.Debug("收到群发命令,未找到任何对应机器人",new{pair,strategyId,cmd});
            foreach (var item in rList)
            {
                try
                {
                    item.OnCmdHandle(cmd); 
                    re++;
                }
                catch (Exception ex)
                {
                    log.Info(ex,item.RobotInfo,cmd);
                }
            }
            return re;
        }
        public bool CommandRobot(string robotName, int? robotId, string cmd)
        {
            Log.Default().Debug($"{robotId},{cmd}");
            //获取当前用户,获取机器人是否存在，内存查询机器人，触发机器人事件
            //触发命令事件，查询在线机器人
            if (robotId == null && string.IsNullOrWhiteSpace(robotName))
            {
                throw new ArgumentException("robotId，robotName必须有一项");
            }
            if (string.IsNullOrWhiteSpace(cmd))
            {
                throw new ArgumentException("cmd不能为空");
            }
            var robot = Robot.GetDicRobot(robotId.Value);
            if (robot == null)
            {
                return false;
            }
            robot.OnCmdHandle(cmd);
            return true;
        }
        RobotInfoStore RobotInfoStore = new RobotInfoStore();
        public RobotInfo[] GetRobotList(int offset, int length, int robotStatus, string label)
        {
            var list = RobotInfoStore.GetRobotList();
            var rList = Robot.GetRobots();
            foreach (var item in list)
            {
              var rb=  rList.FirstOrDefault(p => p.Id == item.Id);
                if (rb!=null)
                {
                    item.Status = 1;
                }
            }
            return list;
        }
        public bool RestartRobot(long RobotId, Dictionary<string, string> Settings = null)
        {
            
            if (Robot.GetDicRobot(RobotId) != null)
            {
                log.Debug($"重复启动机器人{RobotId}");
                return false;
            }
            var info = RobotInfoStore.GetRobotList().FirstOrDefault(p => p.Id == RobotId);
            var robot = new Robot(info);
            robot.Run();
           
         
            //var exchange = new BinanceExchangeImp(info.Key, info.SKey, info.Pair);
            //var robot = new Robot(info.Id, exchange);
            //robot.Name = info.Name;
            //robot.Run();
            //info.Status = 1;
            // var re1 = exchange.ConnTestAsync();
            //log.Info($"{info.Id}:{exchange.GetHashCode()},{info.Key}", re1.Result);
            return true;
        }
        public bool StopRobot(long RobotId)
        {
            var robot = Robot.GetDicRobot(RobotId);
            if(robot==null)
                return false;
            robot.Dispose();
            var info = RobotInfoStore.GetRobotList().FirstOrDefault(p => p.Id == RobotId);
            info.Status = 0;
          
            return true;
        }
        public long NewRobot(string robotName, string exchangeId, string pair, string strategyId, Dictionary<string, string> strategyArgs)
        {
            //账户列表
            //策略列表--参数列表
            var robotInfo = new RobotInfo();
            robotInfo.UserId = 1;
            robotInfo.Name = robotName;
            robotInfo.ExchangeId = exchangeId;
            robotInfo.Pair = pair;
            robotInfo.strategyId = strategyId;
            robotInfo.StrategyArgs = strategyArgs + "";
            var re = DbManager.GetDb().Select<RobotInfo>().Where(p => p.UserId == 1 && p.Name == robotInfo.Name).First();
            if (re != null)
            {
                return 0;
            }
            SetBlankNum(robotInfo);

            return DbManager.GetDb().Insert(robotInfo).ExecuteIdentity();
        }

        /// <summary> 设置次序号，自动填充空白号
        /// 
        /// </summary>
        /// <param name="robotInfo"></param>
        private static void SetBlankNum(RobotInfo robotInfo)
        {
            var list = DbManager.GetDb().Ado.Query<(int, string, int, int)>(@"
select id,Ext1,(select max(Ext1*1) from RobotInfo c) maxExt1,(select count(*) from RobotInfo b where b.ext1*1 <= a.ext1*1 order by b.ext1*1) as rownum from RobotInfo as a 
 where  CAST(rownum as TEXT) <> ext1 or maxExt1*1=Ext1*1
 ORDER BY ext1*1 
 limit 3
");
            if (list.Count<1)
            {
                robotInfo.Ext1 = "1";
                return;
            }
            var item = list.FirstOrDefault();

            var maxNum = item.Item3;
            var rowNum = item.Item4;
            if (maxNum == rowNum)
                robotInfo.Ext1 = (++maxNum).ToString();
            else
                robotInfo.Ext1 = rowNum.ToString();
        }

        public StrategyInfo[] GetStrategyList() {
            return new StrategyStore().GetList();
        }
        public ExchangeInfo[] GetExchangeList()
        {
            return ((IMng<ExchangeInfo>)new QntPlatform.Platform.MngBase<ExchangeInfo>()).GetList(null);
        }
    }

}
